package com.dongjiantong.quarantine.serviceImpl;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.dubbo.config.annotation.Service;
import com.dongjiantong.biz.enums.ReportType;
import com.dongjiantong.biz.model.EarMarkLife;
import com.dongjiantong.biz.model.ReportHandleResumes;
import com.dongjiantong.biz.service.EarMarkLifeWriteService;
import com.dongjiantong.biz.service.ReportHandleResumesService;
import com.dongjiantong.common.utils.ReportNumberMakerUtil;
import com.dongjiantong.common.web.sso.LoginInfo;
import com.dongjiantong.mybatis.ServiceMybatis;
import com.dongjiantong.quarantine.enums.ButcherReportStatus;
import com.dongjiantong.quarantine.enums.FileType;
import com.dongjiantong.quarantine.enums.HarmlessStatus;
import com.dongjiantong.quarantine.enums.ProductType;
import com.dongjiantong.quarantine.mapper.BreedReportsFileMapper;
import com.dongjiantong.quarantine.mapper.DjtButcherAdmissionInspectionsMapper;
import com.dongjiantong.quarantine.mapper.DjtButcherReportsMapper;
import com.dongjiantong.quarantine.mapper.HarmlessMapper;
import com.dongjiantong.quarantine.model.BreedReportsFile;
import com.dongjiantong.quarantine.model.DjtButcherAdmissionInspections;
import com.dongjiantong.quarantine.model.DjtButcherReports;
import com.dongjiantong.quarantine.model.Harmless;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Created by mz on 18/11/17.
 */
@Slf4j
@Service(version = "1.0.0")
public class DjtButcherReportsWriteServiceImpl extends ServiceMybatis<DjtButcherReports> implements DjtButcherReportsWriteService {

    @Resource
    private DjtButcherReportsMapper djtButcherReportsMapper;

    @Resource
    private BreedReportsFileMapper breedReportsFileMapper;

    @Reference(version = "1.0.0")
    private EarMarkLifeWriteService earMarkLifeWriteService;

    @Resource
    private HarmlessMapper harmlessMapper;

    @Resource
    private DjtButcherAdmissionInspectionsMapper djtButcherAdmissionInspectionsMapper;

    @Reference(version = "1.0.0")
    private ReportHandleResumesService reportHandleResumesService;

    /**
     * 新建一单
     *
     * @param djtButcherReports 单据对象
     * @param toStatus          到状态
     * @return Map<String , Object>
     */
    @Override
    public Map<String, Object> create(DjtButcherReports djtButcherReports, Integer toStatus,LoginInfo loginInfo) {

        Map<String, Object> map = Maps.newHashMap();
        Integer fromStatus = djtButcherReports.getStatus();
        String prefix = "T";
        prefix = ReportNumberMakerUtil.createPrefix(prefix, loginInfo.getProvinceId(),loginInfo.getCityId(),loginInfo.getRegionId());//单据编号前缀的开头字母 和 当前用户
        String number = ReportNumberMakerUtil.create(prefix, djtButcherReportsMapper.findCurrentMaxNumber(prefix));
        djtButcherReports.setNumber(number);
        if (toStatus != null && !toStatus.equals(fromStatus)) {
            djtButcherReports.setStatus(toStatus);
            djtButcherReportsMapper.insert(djtButcherReports);
            ReportHandleResumes reportHandleResumes = new ReportHandleResumes();

            reportHandleResumes.setFrom_status(fromStatus.byteValue());
            reportHandleResumes.setReport_id(djtButcherReports.getId());
            reportHandleResumes.setReport_number(number);
            reportHandleResumes.setTo_status(toStatus.byteValue());
            reportHandleResumes.setType(ReportType.SLAUGHTER_QUARANTINE.value());
            reportHandleResumes.setCreated_at(new Date());
            reportHandleResumes.setUpdated_at(new Date());

            reportHandleResumesService.create(reportHandleResumes);

            DjtButcherAdmissionInspections djtButcherAdmissionInspections = djtButcherAdmissionInspectionsMapper.selectByPrimaryKey(djtButcherReports.getAdmission_inspection_id());
            djtButcherAdmissionInspections.setButcher_selected(2);
            djtButcherAdmissionInspections.setRemainder(djtButcherAdmissionInspections.getRemainder() - djtButcherReports.getQuantity());
            djtButcherAdmissionInspections.setSlaughterings(djtButcherAdmissionInspections.getSlaughterings() + djtButcherReports.getQuantity());
            djtButcherAdmissionInspectionsMapper.updateByPrimaryKey(djtButcherAdmissionInspections);

            writeFiles(ReportType.SLAUGHTER_QUARANTINE.value(), FileType.PHOTO.value(), djtButcherReports.getId(), djtButcherReports.getQuarantine_cert_photo_list(), "quarantine_cert_photo_list", "屠宰检疫中产地检疫图片");
            insertToEarLife(djtButcherReports, loginInfo);
            updateAdmissionInspectionEarLife(djtButcherReports, djtButcherAdmissionInspections);
        } else {
            djtButcherReportsMapper.insert(djtButcherReports);
        }
        map.put("id", djtButcherReports.getId());
        return map;
    }

    /**
     * 更新单据
     *
     * @param djtButcherReports 单据对象
     * @param toStatus          到状态
     * @return Boolean
     */
    @Override
    public Map<String, Object> update(DjtButcherReports djtButcherReports, Integer toStatus,LoginInfo loginInfo) {
        Integer fromStatus = djtButcherReports.getStatus();
        Boolean isSuccess;
        Map<String, Object> resultMap = Maps.newHashMap();
        if (toStatus != null && !toStatus.equals(fromStatus)) {
            djtButcherReports.setStatus(toStatus);

            isSuccess = djtButcherReportsMapper.updateByPrimaryKey(djtButcherReports) == 1;

            ReportHandleResumes reportHandleResumes = new ReportHandleResumes();

            reportHandleResumes.setFrom_status(fromStatus.byteValue());
            reportHandleResumes.setReport_id(djtButcherReports.getId());
            reportHandleResumes.setReport_number(djtButcherReports.getNumber());
            reportHandleResumes.setTo_status(toStatus.byteValue());
            reportHandleResumes.setType(ReportType.SLAUGHTER_QUARANTINE.value());
            reportHandleResumes.setCreated_at(new Date());
            reportHandleResumes.setUpdated_at(new Date());

            reportHandleResumesService.create(reportHandleResumes);

            if (fromStatus.equals(ButcherReportStatus.ANEMOMETER_INSPECTION.value())) {
                if (djtButcherReports.getBefore_slaughter_unqualified_quantity() > 0) {
                    Harmless harmless = buildHarmless(djtButcherReports, fromStatus,loginInfo);
                    harmlessMapper.insert(harmless);
                    resultMap.put("harmlessId", harmless.getId());

                    djtButcherReports.setBefore_slaughter_harmless_id(harmless.getId());
                    djtButcherReports.setBefore_slaughter_harmless_number(harmless.getNumber());

                    djtButcherReportsMapper.updateByPrimaryKey(djtButcherReports);
                }
            }
            if (fromStatus.equals(ButcherReportStatus.SYNCHRONOUS_INSPECTION.value())) {
                if (djtButcherReports.getSync_unqualified_quantity() > 0) {
                    Harmless harmless = buildHarmless(djtButcherReports, fromStatus,loginInfo);
                    harmlessMapper.insert(harmless);
                    resultMap.put("harmlessId", harmless.getId());

                    djtButcherReports.setSync_slaughter_harmless_id(harmless.getId());
                    djtButcherReports.setSync_slaughter_harmless_number(harmless.getNumber());

                    djtButcherReportsMapper.updateByPrimaryKey(djtButcherReports);
                }
            }

        } else {
            isSuccess = djtButcherReportsMapper.updateByPrimaryKey(djtButcherReports) == 1;
        }

        resultMap.put("isSuccess", isSuccess);
        return resultMap;
    }

    /**
     * /**
     * 根据id 更新单据的有效状态
     *
     * @param butcherId 单据id
     */
    @Override
    public void updateDeleteFlag(Long butcherId) {
        djtButcherReportsMapper.updateDeleteFlag(butcherId);
    }

    /**
     * 生成无害化对象
     *
     * @param djtButcherReports 屠宰检疫对象
     * @param fromStatus        从状态
     * @return Harmless
     */
    private Harmless buildHarmless(DjtButcherReports djtButcherReports, Integer fromStatus,LoginInfo loginInfo) {

        Harmless harmless = new Harmless();
        String prefix = "WZ";
        if (fromStatus.equals(ButcherReportStatus.ANEMOMETER_INSPECTION.value())) {
            harmless.setReport_type(ReportType.ANEMOMETER_INSPECTION.value());
            harmless.setQuantity(djtButcherReports.getBefore_slaughter_unqualified_quantity().floatValue());
            harmless.setAnimal_type(djtButcherReports.getAnimal_type());
            harmless.setUnit(djtButcherReports.getUnit());
        } else if (fromStatus.equals(ButcherReportStatus.SYNCHRONOUS_INSPECTION.value())) {
            prefix = "WT";
            harmless.setReport_type(ReportType.SYNCHRONOUS_INSPECTION.value());
            harmless.setQuantity(djtButcherReports.getSync_unqualified_quantity());
            harmless.setProduct_type(calculateProductType(djtButcherReports.getExtra()));
            harmless.setUnit(7);//公斤
        }
        prefix = ReportNumberMakerUtil.createPrefix(prefix,loginInfo.getProvinceId(),loginInfo.getCityId(),loginInfo.getRegionId());

        String number = ReportNumberMakerUtil.create(prefix, djtButcherReportsMapper.findCurrentMaxNumber(prefix));

        harmless.setNumber(number);
        harmless.setReport_id(djtButcherReports.getId());
        harmless.setReport_number(djtButcherReports.getNumber());
        harmless.setFactory_owner_id(djtButcherReports.getUser_id());
        harmless.setFactory_owner_name(djtButcherReports.getUser_name());
        harmless.setButcher_farm_id(djtButcherReports.getButcher_farm_id());
        harmless.setButcher_farm_name(djtButcherReports.getButcher_farm_name());
        harmless.setStatus(HarmlessStatus.UNCOMMITTED.value());
        harmless.setCreated_at(new Date());
        harmless.setUpdated_at(new Date());
        harmless.setQuarantine_user_id(loginInfo.getId());
        harmless.setQuarantine_user_name(loginInfo.getRealName());

        return harmless;
    }


    /**
     * 图片或文件的写入
     *
     * @param fileUrls 照片的url
     * @param field    字段名
     * @param state    意义
     */
    private void writeFiles(Integer type1, Integer type2, Long relevanceId, List<String> fileUrls, String field, String state) {
        if (fileUrls != null && !fileUrls.isEmpty()) {
            for (String string : fileUrls) {
                BreedReportsFile breedReportsFile = new BreedReportsFile();
                breedReportsFile.setType1(type1);
                breedReportsFile.setType2(type2);
                breedReportsFile.setField(field);
                breedReportsFile.setAddress(string);
                breedReportsFile.setRelevance_id(relevanceId);
                breedReportsFile.setState(state);
                breedReportsFile.setDate(new Date());
                breedReportsFileMapper.insert(breedReportsFile);
            }
        }
    }

    /**
     * 耳标使用记录的写入
     *
     * @param djtButcherReports 屠宰对象
     */
    private void insertToEarLife(DjtButcherReports djtButcherReports, LoginInfo loginInfo) {
        List<String> earTagNumbers = djtButcherReports.getEar_tag_numbers();
        if (earTagNumbers != null && !earTagNumbers.isEmpty()) {
            List<EarMarkLife> earMarkLives = null;
            for (String earTagNumber : earTagNumbers) {
                earMarkLives = new ArrayList<>();
                EarMarkLife earMarkLife = new EarMarkLife();

                earMarkLife.setMark_number(earTagNumber);
                earMarkLife.setReport_id(djtButcherReports.getId());
                earMarkLife.setReport_name(djtButcherReports.getNumber());
                earMarkLife.setReport_type(ReportType.SLAUGHTER_QUARANTINE.value());
                earMarkLife.setMark_type(djtButcherReports.getAnimal_type());
                earMarkLife.setOperator_id(loginInfo.getId());
                earMarkLife.setOperator_name(loginInfo.getRealName());
                earMarkLife.setIs_selected(1);
                earMarkLife.setCreated_at(new Date());

                earMarkLives.add(earMarkLife);
            }
            earMarkLifeWriteService.insertList(earMarkLives);
        }
    }

    /**
     * 入场耳标的life 操作（被选择）
     *
     * @param djtButcherReports              屠宰单据
     * @param djtButcherAdmissionInspections 入场单据
     */
    private void updateAdmissionInspectionEarLife(DjtButcherReports djtButcherReports, DjtButcherAdmissionInspections djtButcherAdmissionInspections) {

        List<String> earTagNumbers = djtButcherReports.getEar_tag_numbers();

        if (earTagNumbers != null && !earTagNumbers.isEmpty()) {
            Map<String, Object> map = Maps.newHashMap();

            map.put("isSelected", 2);
            map.put("earTagNumbers", earTagNumbers);
            map.put("reportId", djtButcherAdmissionInspections.getId());
            map.put("reportType", ReportType.ADMISSION_INSPECTION.value());
            map.put("markType", djtButcherAdmissionInspections.getProduct_type());

            earMarkLifeWriteService.updateMarks(map);
        }
    }

    private String calculateProductType(Map<String, Double> extra) {
        Double headerNum = extra.get("head");
        Double ketoneBody = extra.get("carcass");
        Double internal = extra.get("visceral");

        if (headerNum != 0f && ketoneBody != 0f && internal != 0f) {
            return ProductType.HEAD_INTERNAL_KET.toString();
        }
        if (headerNum != 0f && ketoneBody != 0f) {
            return ProductType.HEAD_KET.toString();
        }
        if (headerNum != 0f && internal == 0f) {
            return ProductType.HEAD.toString();
        }
        if (ketoneBody != 0f && internal == 0f) {
            return ProductType.KET.toString();
        }
        if (headerNum != 0f) {
            return ProductType.HEAD_INTERNAL.toString();
        }
        if (ketoneBody != 0f) {
            return ProductType.INTERNAL_KET.toString();
        }
        if (internal != 0f) {
            return ProductType.INTERNAL.toString();
        }
        return null;
    }

}
